<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class AdminerIdertity extends CUserIdentity
{
	/**
	 * Authenticates a user.
	 * The example implementation makes sure if the username and password
	 * are both 'demo'.
	 * In practical applications, this should be changed to authenticate
	 * against some persistent user identity storage (e.g. database).
	 * @return boolean whether authentication succeeds.
	 */
	private $_id;
	
	public function __construct($username,$password)
	{
		$this->username=$username;
		$this->password=$password;
	}
	
	public function authenticate()
	{
		$user = Adminer::model()->findByAttributes(array('zda_username' => $this->username));
		//print_r($user);exit;
		if ($user === null) {
			$this->errorCode = "用户名无效！";
		} else{
			if ($user->zda_password !== $user->passwordEncode($this->password)) {
					$this->errorCode = "密码不正确！";
			} else if(!$this->checkIp()){
				$this->errorCode = "你的IP段不允许访问！";
			} else {
				$this->_id = $user->zda_id;
				$this->errorCode = self::ERROR_NONE;
			}
		}
		return $this->errorCode;
	}
	
	public function getId(){
		return $this->_id;
	}
	
	public function getName()
	{
		return $this->username;
	}
	
	public function getPersistentStates()
	{
		return array('manage'=>'admin');
	}
	
	/**
	 *商家子账户IP效验
	 */
	public function checkIp(){
		//若IP限制关闭，直接跳过
		if(!F::setting('manage_securityIp_limit'))
			return true;
		
		//获取配置的安全IP信息。
		$ipdata = unserialize(F::Setting('security_ip'));
		$user_ip = Yii::app()->request->getUserHostAddress();
		if(in_array($user_ip,$ipdata)){
			return true;
		}else{
			return false;
		}
	}
}